import http from "./http";
import {_dev} from "../config/api";
import {Toast} from "antd-mobile";
const {location,alert,encodeURIComponent } = window;

const code = {
  /**
   * 鉴权
   * @param obj
   * @returns {Promise<unknown>}
   */
  async config(obj){
  
    let url = location.href;
     let data = await http.post('/wxapisg/getCorpSign',{
       url,
      //  hosId:window.hos.hosId
       hosId:window.localStorage.getItem("hosId") || window.hos.hosId
     });
     console.log("权限列表",data)
    data.url = url;
    window.wx.config({
      beta: true,// 必须这么写，否则wx.invoke调用形式的jsapi会有问题
      debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
      appId: 'ww88d1beb4815fa054', // 必填，企业微信的corpID
      timestamp: data.timestamp, // 必填，生成签名的时间戳
      nonceStr: data.nonceStr, // 必填，生成签名的随机串
      signature: data.signature,// 必填，签名，见 附录-JS-SDK使用权限签名算法
      jsApiList: [...obj.jsApiList,'shareWechatMessage']  // 必填，需要使用的JS接口列表，凡是要调用的接口都需要传进来
    });
    window.wx.error(err=>{
      alert('config-err'+JSON.stringify(err))}
      )
    return new Promise(resolve => {
      window.wx.ready(()=>{
        resolve(data)
     
        window.wx.hideOptionMenu();
      });
    })
  },
  /**
   * 外部联系人鉴权
   * @param obj
   * @returns {Promise<unknown>}
   */
  async agentConfig(obj){
    let data = await http.post('/wxapisg/getAppSignature',{
      nonceStr:obj.nonceStr,
      timestamp:obj.timestamp,
      url:obj.url
    });
    
    console.log("appSign",data)

    return new Promise(resolve => {
      // wechatdevtools


      window.wx.agentConfig({
        beta: true,// 必须这么写，否则wx.invoke调用形式的jsapi会有问题
        corpid: 'ww88d1beb4815fa054', // 必填，企业微信的corpid，必须与当前登录的企业一致
        agentid: '1000003', // 必填，企业微信的应用id （e.g. 1000247）
        timestamp: obj.timestamp, // 必填，生成签名的时间戳
        nonceStr: obj.nonceStr, // 必填，生成签名的随机串
        signature: data.signature,// 必填，签名，见附录-JS-SDK使用权限签名算法
        // jsApiList:  obj.jsApiList , //必填
        jsApiList:  ['getContext','getCurExternalContact','sendChatMessage','shareWechatMessage'] , //必填
        success: ()=>{
          resolve('ok')
          console.log("执行成功")
        },
        fail:err=>{
          // console.log(err)
          alert('agentConfig-err'+JSON.stringify(err))
        }
      });

    })
  },
  /**
   * 合并鉴权
   * @param jsApiList 注入权限
   * @returns {Promise<unknown>}
   */


  async getOutUserId(jsApiList = []){
    return new Promise(resolve => {
      window.wx.invoke('getCurExternalContact',{},res=> {
        if (res.err_msg === "getCurExternalContact:ok") {
          resolve(res.userId);
        }else {
          alert('获取外部联系人id失败')
        }
      })
    })
  },
  /**
   * 合并鉴权
   * @param jsApiList 注入权限
   * 获取当前页面入口
   * @returns {Promise<unknown>}
   */
  async getContext(jsApiList = []){
    let data = await code.config({jsApiList:['agentConfig']})
    let ok = await code.agentConfig({
      ...data,
      jsApiList:['getContext',...jsApiList]
    });
    return new Promise(resolve => {
      window.wx.invoke('getContext', {}, function(res){
        if(res.err_msg == "getContext:ok"){
          //返回进入H5页面的入口类型，目前有normal、contact_profile、single_chat_tools、group_chat_tools、chat_attachment
          console.log("进入成功")
          resolve(res.entry);
        }else {
          alert('获取当前页面入口失败')
        }
      });
    })
  },

  /**
   * 分享信息
   * 
   */
   async shareContext(param){
    let data = await code.config({jsApiList:['agentConfig','shareWechatMessage']})
    let ok = await code.agentConfig({
      ...data,
      jsApiList:['getContext','shareWechatMessage']
    });
    return new Promise(resolve => {
      // window.wx.invoke('getContext', {}, function(res){
      //   if(res.err_msg == "getContext:ok"){
      //     //返回进入H5页面的入口类型，目前有normal、contact_profile、single_chat_tools、group_chat_tools、chat_attachment
      //     console.log("进入成功")
      //     resolve(res.entry);
      //   }else {
      //     alert('获取当前页面入口失败')
      //   }
      // });

       window.wx.invoke(
            "shareWechatMessage", {
                    title: '在线开单收款', // 分享标题
                    desc: '广州曙光医院', // 分享描述
                    link: param, // 分享链接
                    imgUrl: "http://image.sgwxmini.com/logo.jpg" // 分享封面
        }, function(res) {
            console.log("分享",res)
            if (res.err_msg == "shareWechatMessage:ok") {
            }
        }
        );

    })
  },


  /**
   * 员工信息，且绑定手机号
   * @returns {Promise<unknown>}
   */

  async checkBind(){  
    let url = window.location.pathname;
    let user = await code.getUser();
    let data = await http.outPost('/wxapisg/checkBindManagerId',{
      userId:user.userid,
      // userId: 'SG03133', // 暂时写死
      // hosId:window.hos.hosId
      // hosId:window.localStorage.getItem("hosId") || window.hos.hosId
    })
    user.managerId=data?.managerId?data?.managerId:""
    window.localStorage.setItem('user',JSON.stringify(user))

    // data.hosId=window.hos.hosId
    data.hosId= window.localStorage.getItem("hosId") || window.hos.hosId
    window.localStorage.setItem('check',JSON.stringify(data));
    console.log(data)
    console.log("url-code:",url)
    if(data.isBind===0 || !data.hosId){
      sessionStorage.removeItem('loginStatus')
      window.location.href = '/login?url='+url;
    }

    return data;

  },

  /**
   * 员工信息，且绑定手机号
   * @returns {Promise<unknown>}
   */

  async getUser(){
    
    let useridBool = window.localStorage.getItem('user') ? JSON.parse(window.localStorage.getItem('user')) : ''
    if(useridBool != '' && useridBool.userid == ''){
      window.localStorage.clear()
    }

    let user = JSON.parse(localStorage.getItem('user')) ;
    if(user){
      // user.hosId=window.hos.hosId
      user.hosId= window.localStorage.getItem("hosId") || window.hos.hosId
      window._user = user;
      return window._user
    };
    let url = location.href; //encodeURIComponent 
    console.log("url:",url)
    if(url.indexOf('code=')>0){ 
      url.match(/code=(.+)&/i);
      let _user = await http.outPost('/wxapisg/getCorpCode',{
        code:RegExp["$1"],
        // hosId:window.hos.hosId
        hosId:window.localStorage.getItem("hosId") || window.hos.hosId

      })
      console.log(_user) 
      // _user.hosId=window.hos.hosId
      _user.hosId=window.localStorage.getItem("hosId") || window.hos.hosId
     localStorage.setItem('user',JSON.stringify(_user));
      return new Promise(resolve => {
        console.log(_user)

        if(url.indexOf('/informationSettings') != -1 || url.indexOf('/login') != -1){
          localStorage.setItem('user',JSON.stringify(_user));
          window._user = _user;
          resolve(_user)
          return false
        }

        if(_user.isBind){
          console.log("已绑定")
         localStorage.setItem('user',JSON.stringify(_user));
          window._user = _user;
          resolve(_user)
        }else {
          console.log("未绑定",url.indexOf('/yuyue?'))
          Toast.fail('用户未绑定',1.5,function (){
            window.location.href = `/login`;
          })
        }
      })
    }else {
      location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?' +
          'appid=ww88d1beb4815fa054' +
          '&redirect_uri='+ encodeURIComponent(url)+
          '&response_type=code&scope=snsapi_base&agentid=1000009&state=STATE#wechat_redirect'
    }
  }
}

export default code;

/**
 * 日期格式化
 * @param date
 * @param fmt yyyy-MM-dd hh:mm:ss
 * @returns {*} yyyy-MM-dd hh:mm:ss
 */
export const dateFormat = (date,fmt)=>{
  const o = {
    "M+" : date.getMonth()+1,                 //月份
    "d+" : date.getDate(),                    //日
    "h+" : date.getHours(),                   //小时
    "m+" : date.getMinutes(),                 //分
    "s+" : date.getSeconds(),                 //秒
    "q+" : Math.floor((date.getMonth()+3)/3), //季度
    "S"  : date.getMilliseconds()             //毫秒
  };
  if(/(y+)/.test(fmt)) {
    fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));
  }
  for(let k in o) {
    if(new RegExp("("+ k +")").test(fmt)){
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length===1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
    }
  }
  return fmt;
}

/**
 * 发送消息
 * @param link 链接
 * @param title 标题
 * @param desc 副标题
 * @returns {Promise<void>}
 */
export const sendMsg= async (link,title,desc='')=>{
  if(_dev) return ;
  const outUserId = await code.getOutUserId(['sendChatMessage']);
  console.log('outUserId111:',outUserId);
  window.wx.invoke('sendChatMessage', {
    msgtype:'news', news:{link, title, desc, imgUrl: "http://work.arsmo.cn/aaa.png"}
  });
};

/*
{"errcode":0,"errmsg":"ok","userid":"ChengJingBo","name":"程敬博",
"department":[1170011048],"position":"","mobile":"13213243312",
"gender":"1","email":"",
"avatar":"http://wework.qpic.cn/bizmail/tYaYvsaVnO4wOkAbzic6eYjibzTZo33O3iaZQiaV77bSxWF7z5KtTBW1HQ/0",
"status":1,"isleader":0,"extattr":{"attrs":[]},"english_name":"",
"telephone":"","enable":1,"hide_mobile":0,"order":[0],
"external_profile":{"external_attr":[],"external_corp_name":""},
"main_department":1170011048,
"qr_code":"https://open.work.weixin.qq.com/wwopen/userQRCode?vcode=vc03aceea5da920ef7",
"alias":"","is_leader_in_dept":[0],"address":"",
"thumb_avatar":"http://wework.qpic.cn/bizmail/tYaYvsaVnO4wOkAbzic6eYjibzTZo33O3iaZQiaV77bSxWF7z5KtTBW1HQ/100",
"apistatus":1,"open_id":"oHiNy0x55duLJk6HU6738COx2Y_Q","hosId":"0"}
 */